package co.za.itweb.itwebafrica;


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;




public class AndroidBasicOAuthActivity extends FragmentActivity {
	public int TWITTER_AUTH;
	public Twitter mTwitter;
	public RequestToken mRequestToken;
	public String accessToken;
	public String accessTokenSecret;
	
	public boolean haveConnectedWifi;
	public boolean haveConnectedMobile;
	public double x;


	/** Called when the activity is first created. */
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);

		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(AndroidBasicOAuthActivity.this);
		accessToken = settings.getString( "twitter_access_token", null );
		accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
		Button tweetB = (Button) findViewById(R.id.tweet_button);
		
		tweetB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			
				updateStatus();

			}
		});

		new TweetTask().execute();


	}
	private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}


	private void updateStatusLoggedIn() {
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		accessToken = settings.getString( "twitter_access_token", null );
		accessTokenSecret = settings.getString( "twitter_access_token_secret", null );

		// String s2 = String.valueOf(i);
		// Toast.makeText(this, s2, 10000).show();
		ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
		builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
		builder.setOAuthAccessToken(accessToken);
		builder.setOAuthAccessTokenSecret(accessTokenSecret);
		Configuration conf = builder.build();
		Twitter t = new TwitterFactory(conf).getInstance();
		int i = 0;
		i++;
		try {
			if(i<10){
				t.updateStatus( "Loggedin" + i);
			}
		}
		catch (TwitterException e) {
			e.printStackTrace();
		}

	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	


		if (requestCode == TWITTER_AUTH)
		{

			if (resultCode == Activity.RESULT_OK)
			{
				Toast.makeText(this, "Hey Ho", Toast.LENGTH_SHORT).show();
				String oauthVerifier = (String) data.getExtras().get("oauth_verifier");
                
				AccessToken at = null;

				try
				{
					// Pair up our request with the response
					at = mTwitter.getOAuthAccessToken(oauthVerifier);
					String theToken = at.getToken();
						Toast.makeText(this, theToken, Toast.LENGTH_SHORT).show();
					String theTokenSecret = at.getTokenSecret();
						Toast.makeText(this, theTokenSecret, Toast.LENGTH_SHORT).show();
					SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
					settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("twitter_access_token",theToken);
					editor.putString("twitter_access_token_secret", theTokenSecret);
					editor.commit();


					updateStatus();
				}
				catch (TwitterException e)
				{
					e.printStackTrace();
				}
			}
		}
		else
		{
			Toast.makeText(this, "uh oh, Spaghetti Os", Toast.LENGTH_SHORT).show();
		}

	}
	private void updateStatus() {
		
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		accessToken = settings.getString( "twitter_access_token", null );
		accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
			Toast.makeText(this, accessToken, Toast.LENGTH_SHORT).show();
			Toast.makeText(this, accessTokenSecret, Toast.LENGTH_SHORT).show();
		haveNetworkConnection();
		if ((haveConnectedWifi)|| (haveConnectedMobile)){
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
			builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
			builder.setOAuthAccessToken(accessToken);
			builder.setOAuthAccessTokenSecret(accessTokenSecret);
			Configuration conf = builder.build();
			Twitter t = new TwitterFactory(conf).getInstance();

			try {
				x = Math.random();
				t.updateStatus( "Yo ho ho and a bottle of rum " + x);

			}
			catch (TwitterException e) {
				e.printStackTrace();
			}
		}
		else{
			Toast.makeText(this, "No access to Internet..please try again", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void onResumeIt() {
		
		
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		accessToken = settings.getString( "twitter_access_token", null );
		accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
		haveNetworkConnection();
		if ((haveConnectedWifi)|| (haveConnectedMobile)){
			

			if ((accessToken==null)||(accessTokenSecret==null)){
				mTwitter = new TwitterFactory().getInstance();
				mRequestToken = null;
				mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET );
				String callbackURL = getResources().getString(R.string.twitter_callback);
				try
				{
					mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
				}
				catch (TwitterException e)
				{
					e.printStackTrace();
				}
				Intent i = new Intent(getApplicationContext(), TwitterWebviewActivity.class);
				i.putExtra("URL", mRequestToken.getAuthenticationURL());
				startActivityForResult(i, TWITTER_AUTH);
			}
			else{
				Toast.makeText(this, "Token found..logged in", Toast.LENGTH_SHORT).show();
				 updateStatusLoggedIn();
			}
		}
		else{
			Toast.makeText(this, "No access to Internet..please try again", Toast.LENGTH_SHORT).show();
			Intent i = new Intent(this, CheckNetAccess.class);
			startActivity(i);
		}
	}
	
	public class TweetTask extends AsyncTask<Void, Void, Integer> {
 
		
		

		protected Integer doInBackground(Void... params) {
			
			SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

			accessToken = settings.getString( "twitter_access_token", null );
			accessTokenSecret = settings.getString( "twitter_access_token_secret", null );
			haveNetworkConnection();
			if ((haveConnectedWifi)|| (haveConnectedMobile)){
				

				if ((accessToken==null)||(accessTokenSecret==null)){
					mTwitter = new TwitterFactory().getInstance();
					mRequestToken = null;
					mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,Constants.CONSUMER_SECRET );
					String callbackURL = 
							getResources().getString(R.string.twitter_callback);
					try
					{
						mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
						return (Integer) 1;
					}
					catch (TwitterException e)
					{
						e.printStackTrace();
					}
					
//					Intent i = new Intent(getApplicationContext(), TwitterWebviewActivity.class);
//					i.putExtra("URL", mRequestToken.getAuthenticationURL());
//					startActivityForResult(i, TWITTER_AUTH);
				}
				else{
					
					Toast.makeText(getApplicationContext(), "Token found..logged in", Toast.LENGTH_SHORT).show();
					 updateStatusLoggedIn();
					return 0;
				}
			}
			else{
//				Toast.makeText(this, "No access to Internet..please try again", 3000).show();
				Intent i = new Intent(getApplicationContext(), CheckNetAccess.class);
				startActivity(i);
				return 0;
			}
		

			return 0;
		}

		
	

	@Override
	protected void onPostExecute(Integer result) {
		if(result==1){
			startIt();
		}
	}




	
	}
	public void startIt() {
		Intent i = new Intent(AndroidBasicOAuthActivity.this, TwitterWebviewActivity.class);
		i.putExtra("URL", mRequestToken.getAuthenticationURL());
		startActivityForResult(i, TWITTER_AUTH);
		
	}

}